﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Web.Security;
using TBM.Core;
using System.Data;

namespace TBM.Filters
{
    public class ActionFilters : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //执行action后执行这个方法 比如做操作日志
        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 加载用户信息
            if (HttpRuntime.Cache.Get("User") == null)
            {
                string UID = HttpContext.Current.User.Identity.Name;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = new SqlConnection(Config.ConnectionString);
                cmd.Connection.Open();
                cmd.CommandText = "select [UID], FirstName, LastName, Email, Phone, QQ, Memo from dbo.Users where [UID] = @UID";
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
                cmd.Parameters["@UID"].Value = UID;

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        TBM.Models.User user = new Models.User
                        {
                            UID = dr["UID"].ToString(),
                            FirstName = dr["FirstName"].ToString(),
                            LastName = dr["LastName"].ToString(),
                            Email = dr["Email"].ToString(),
                            Phone = dr["Phone"].ToString(),
                            QQ = dr["QQ"].ToString(),
                            Memo = dr["Memo"].ToString()
                        };

                        HttpRuntime.Cache.Insert("User", user);
                    }
                }

                if (cmd.Connection.State != ConnectionState.Closed)
                {
                    cmd.Connection.Close();
                }
            }
        }
    }
}